import hashlib
import os
import time
from datetime import datetime, timedelta
from flask import render_template, request, jsonify, current_app, g, redirect, url_for
from sqlalchemy import extract

from app2 import db
from app2.models.models import User, Category, News, Order, Goods
from app2.utils.common.common import login_user_data2
from . import admin_blue


@admin_blue.route("")
@login_user_data2
def index():
    # 設置管理員權限登陸
    if (g.user and g.user.is_admin == 1):
        # 查询所有用户
        user_num = db.session.query(User).count()
        now_time = datetime.now()
        print(now_time)

        # 前7天的用户活跃度

        data_dict = dict()
        begin_date = now_time - timedelta(days=6)

        for i in range(0, 7):
            # 计算当前日期
            cur_date = begin_date + timedelta(days=i)
            # 获取年月日
            year = cur_date.year
            month = cur_date.month
            day = cur_date.day

            # 计算出每天添加的用户
            everyday_num = db.session.query(User).filter(extract('year', User.last_login) == year,
                                                         extract('month', User.last_login) == month,
                                                         extract('day', User.last_login) == day).count()

            # # 添加到字典中
            date_str = cur_date.strftime("%Y-%m-%d")
            data_dict[date_str] = everyday_num

        print(data_dict)
        # data_dict = {'2019-06-17': 100, '2019-06-18': 0, '2019-06-19': 80, '2019-06-20': 0, '2019-06-21': 10 , '2019-06-22': 1, '2019-06-23': 1}
        return render_template("admin/index_new.html", user=g.user, data_dict=data_dict)
    else:
        return redirect(url_for('index_blue.index'))


@admin_blue.route("/resource")
@login_user_data2
def resource():
    # 资源分享
    resources = db.session.query(News).filter(News.category_id == 2).all()
    return render_template("admin/resource.html", user=g.user, resources=resources)


@admin_blue.route("/technology")
@login_user_data2
def technology():
    # 技术教程
    technologys = db.session.query(News).filter(News.category_id == 3).all()
    return render_template("admin/technology.html", user=g.user, technologys=technologys)


@admin_blue.route("/resource_vip")
@login_user_data2
def resource_vip():
    # VIP资源
    resource_vips = db.session.query(News).filter(News.category_id == 4).all()
    return render_template("admin/resource_vip.html", user=g.user, resource_vips=resource_vips)


@admin_blue.route("/hardware")
@login_user_data2
def hardware():
    # 硬件相关
    hardwares = db.session.query(News).filter(News.category_id == 5).all()
    return render_template("admin/hardware.html", user=g.user, hardwares=hardwares)


@admin_blue.route("/hot_spot")
@login_user_data2
def hot_spot():
    # 热点资讯
    hot_spots = db.session.query(News).filter(News.category_id == 6).all()
    return render_template("admin/hot_spot.html", user=g.user, hot_spots=hot_spots)


@admin_blue.route("/user_count")
@login_user_data2
def user_count():
    # 计算用户总数
    total_count = db.session.query(User).count()
    # 计算用户日新增数
    now_date = datetime.now()
    year = now_date.year
    month = now_date.month
    month_count = db.session.query(User).filter(extract('year', User.create_time) == year,
                                                extract('month', User.create_time) == month).count()
    day = now_date.day
    day_count = db.session.query(User).filter(extract('year', User.create_time) == year,
                                              extract('month', User.create_time) == month,
                                              extract('day', User.create_time) == day).count()

    counts_li = []
    date_li = []
    begin_date = now_date - timedelta(days=29)

    for i in range(0, 30):
        # 计算当前的日期
        cur_date = begin_date + timedelta(days=i)

        # 获取当前日期的年月日
        year = cur_date.year
        month = cur_date.month
        day = cur_date.day

        # 计算出当天新增用户数量
        count = db.session.query(User).filter(extract('year', User.create_time) == year,
                                              extract('month', User.create_time) == month,
                                              extract('day', User.create_time) == day).count()
        # 保存到新增用户数量counts_li列表中
        counts_li.append(count)

        # 保存当前日期
        date_str = cur_date.strftime('%Y-%m-%d')
        date_li.append(date_str)

    return render_template("admin/user_count.html",
                           total_count=total_count,
                           month_count=month_count,
                           day_count=day_count,
                           counts_li=counts_li,
                           date_li=date_li
                           )


@admin_blue.route("/pt_user_list")
@login_user_data2
def pt_user_list():
    """普通用户列表"""
    paginate = db.session.query(User).filter(User.vip == 0).order_by(User.create_time.desc()).all()
    user_list = [x.to_user_list_dict() for x in paginate]
    return render_template("admin/pt_user_list.html", user=g.user, user_list=user_list)


@admin_blue.route("/vip_user_list")
@login_user_data2
def vip_user_list():
    """VIP用户列表"""
    paginate = db.session.query(User).filter(User.vip == 1).order_by(User.create_time.desc()).all()
    user_list = [x.to_user_list_dict() for x in paginate]
    return render_template("admin/vip_user_list.html", user=g.user, user_list=user_list)


@admin_blue.route("/orders")
@login_user_data2
def orders():
    order_list = db.session.query(Order).order_by(Order.create_time).all()
    order_s = [x.user_order_good() for x in order_list]
    return render_template("admin/orders.html", order=order_s, user=g.user)


# @admin_blue.route("/user_list")
# def user_list():
#     """用户列表"""
#     page = request.args.get('page')
#     page = int(page) if page and page.isdigit() else 1
#     paginate = db.session.query(User).order_by(User.create_time.desc()).paginate(page, 2, False)
#     user_list = [x.to_user_list_dict() for x in paginate.items]
#     return render_template("admin/user_list.html", user_list=user_list, paginate=paginate)


@admin_blue.route("/news_review")
def news_review():
    """新闻审核"""
    page = request.args.get('page')
    page = int(page) if page and page.isdigit() else 1
    paginate = db.session.query(News).order_by(News.create_time.desc()).paginate(page, 10, False)
    news_list = [x.to_news_list_dict() for x in paginate.items]
    return render_template("admin/news_review.html", paginate=paginate, news_list=news_list)


@admin_blue.route("/news_review_detail/<news_id>", methods=["GET", "POST"])
def news_review_detail(news_id):
    """新闻审核详情页"""
    news = db.session.query(News).filter(News.id == news_id).first()

    if request.method == "GET":
        return render_template("admin/news_review_detail.html", news=news)
    if request.method == "POST":
        action = request.json.get('action')
        reason = request.json.get('reason')
        try:
            if action == "accept":  # 审核通过
                news.status = 0
            elif action == "reject":
                news.status = -1
            news.reason = reason
            db.session.commit()
            ret = {
                "errno": 0,
                "errmsg": "操作成功"
            }
        except Exception as e:
            print('try错误信息', e)
            ret = {
                "errno": 6003,
                "errmsg": "操作失败"
            }
        return jsonify(ret)


@admin_blue.route("/news_edit")
def news_edit():
    """新闻板式编辑(查询网站所有新闻)"""
    page = request.args.get('page')
    page = int(page) if page and page.isdigit() else 1
    paginate = db.session.query(News).order_by(News.create_time.desc()).paginate(page, 10, False)
    news_list = [x.to_news_list_dict() for x in paginate.items]
    return render_template("admin/news_edit.html", paginate=paginate, news_list=news_list)


@admin_blue.route("/news_edit_detail/<news_id>", methods=["GET", "POST"])
def news_edit_detail(news_id):
    """新闻板式编辑(当前新闻)"""
    news = db.session.query(News).filter(News.id == news_id).first()

    if request.method == "GET":
        # 查询当前新闻
        # 查询当前的网站新闻分类
        category = db.session.query(Category).filter(Category.id != 1).all()
        return render_template("admin/news_edit_detail.html", news=news, category=category)
    elif request.method == "POST":
        title = request.form.get("title")
        category = request.form.get("category")
        digest = request.form.get("digest")
        content = request.form.get("content")
        f = request.files.get("image")
        if not all([title, category, digest, content]):
            ret = {
                "errno": 6001,
                "errmsg": "缺少参数"
            }
            return jsonify(ret)

        # 保存图片
        if f:
            image_name = f.filename
            hash_name = hashlib.md5()
            hash_name.update((f.filename+str(time.time())).encode('utf-8'))
            f_name = hash_name.hexdigest() + image_name[image_name.rfind("."):]
            save_path = os.path.join(current_app.root_path, "static/upload/images", f_name)
            display_path = os.path.join("/static/upload/images", f_name)
            f.save(save_path)
            news.index_image_url = display_path

        try:
            news.title = title
            news.category_id = category
            news.digest = digest
            news.content = content
            db.session.commit()
            ret = {
                "errno": 0,
                "errmsg": "编辑成功"
            }

        except Exception as e:
            print("try错误信息", e)
            ret = {
                "errno": 6004,
                "errmsg": "编辑失败"
            }
        return jsonify(ret)


@admin_blue.route("/news_type", methods=["POST", "GET"])
def news_type():
    """新闻分类管理"""
    if request.method == "GET":
        news_type = db.session.query(Category).filter(Category.id != 1).all()
        return render_template("admin/news_type.html", news_type=news_type)
    elif request.method == "POST":
        name = request.json.get('name')
        id = request.json.get('id')

        if not name:
            ret = {
                "errno": 6001,
                "errmsg": "缺少参数"
            }
            return jsonify(ret)

        print(id)
        try:
            if id:
                c = db.session.query(Category).filter(Category.id == id).first()
                c.name = name
            else:
                category = Category(name=name)
                db.session.add(category)
            db.session.commit()
            ret = {
                "errno": 0,
                "errmsg": "操作成功"
            }

        except Exception as e:
            print("try错误信息", e)
            ret = {
                "errno": 6002,
                "errmsg": "操作失败"
            }
        return jsonify(ret)



